package cn.codeforfun.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @author wangbin
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration {

    @Configuration
    @Profile({"!unit-test & !integration-test"})
    public static class DefaultConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/user/public").permitAll()
                    .anyRequest().authenticated()
            ;
        }
    }

    @Configuration
    @Profile({"unit-test | integration-test"})
    public static class TestConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/user/public").permitAll()
                    .anyRequest().authenticated()
            ;
        }

        /**
         * 由于security-oauth2默认是无状态的，那么单元测试中就无法模拟用户及用户权限。
         * 所以在单元测试时，如果要模拟用户及用户权限，就要临时关闭无状态
         */
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.stateless(false);
        }
    }

}
